'''
@author: wangxutao 
@project: ZetCore
@file: time.py
@time: 2019/12/3 15:02
@desc:
'''
import time
from datetime import datetime


def timestamp_2_datetime_str(time_stamp, format_string='%Y-%m-%d %H:%M:%S'):
    if len(str(int(time_stamp))) == 13:
        time_stamp = float(float(time_stamp) / 1000)
    else:
        time_stamp = float(time_stamp)
    time_stamp = time.localtime(time_stamp)
    return time.strftime(format_string, time_stamp)


def timestamp_2_datetime(time_stamp):
    if len(str(int(time_stamp))) == 13:
        time_stamp = float(float(time_stamp) / 1000)
    else:
        time_stamp = float(time_stamp)
    return datetime.fromtimestamp(time_stamp)


def datetime_2_timestamp(date_time, format_string='%Y-%m-%d %H:%M:%S'):
    if type(date_time) == str:
        date_time = datetime.strptime(date_time, format_string)

    unix_time_stamp = time.mktime(date_time.timetuple())
    return int(unix_time_stamp*1000)


# 转换时间格式到字符串
def human_datetime(date=None):
    if date:
        assert isinstance(date, datetime)
    else:
        date = datetime.now()
    return date.strftime('%Y-%m-%d %H:%M:%S')


# 转换时间格式到字符串(天)
def human_date(date=None):
    if date:
        assert isinstance(date, datetime)
    else:
        date = datetime.now()
    return date.strftime('%Y-%m-%d')

def human_time(date=None):
    if date:
        assert isinstance(date, datetime)
    else:
        date = datetime.now()
    return date.strftime('%H:%M:%S')


# 解析时间类型的数据
def parse_time(value):
    if isinstance(value, datetime):
        return value
    if isinstance(value, str):
        if len(value) == 10:
            return datetime.strptime(value, '%Y-%m-%d')
        elif len(value) == 19:
            return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
    raise TypeError('Expect a datetime value')


# 传两个时间得到一个时间差
def human_diff_time(time1, time2):
    time1 = parse_time(time1)
    time2 = parse_time(time2)
    delta = time1 - time2 if time1 > time2 else time2 - time1
    if delta.seconds < 60:
        text = '%d秒' % delta.seconds
    elif delta.seconds < 3600:
        text = '%d分' % (delta.seconds / 60)
    else:
        text = '%d小时' % (delta.seconds / 3600)
    return '%d天%s' % (delta.days, text) if delta.days else text